<template>
  <view :data-theme="theme">
    <CustomNavbar title="用户登录" :left-icon="false"></CustomNavbar>
    <basic-components :loading-other="false" />

    <view v-if="!loading" class="login-form">
      <!-- 睿赛珂生产管理系统 -->
      <view class="head">
        <view class="img">
          <image src="@/assets/logo.png" />
        </view>
        睿赛珂生产管理系统 <text class="version-code" v-if="useVersionCode">(v.{{ useVersionCode }})</text>
      </view>
      <uni-forms ref="userForm" label-position="left" :model-value="userInfo" :rules="rules">
        <uni-forms-item prop="username" border-bottom>
          <uni-easyinput
            v-model="userInfo.username"
            :placeholder-style="placeholderStyle"
            placeholder="请输入账号"
            :input-border="false"
          />
        </uni-forms-item>

        <uni-forms-item prop="password" border-bottom>
          <uni-easyinput
            v-model="userInfo.password"
            :placeholder-style="placeholderStyle"
            type="password"
            placeholder="请输入密码"
            :input-border="false"
          />
        </uni-forms-item>

        <!-- <view class="agreement">
          <view class="relative">
            <u-checkbox-group>
              <u-checkbox
                v-model="userInfo.agreement"
                :active-color="globalTheme.basicColor.primary"
                size="16px"
                checked
                :name="true"
                @change="checkboxChange"
              />
            </u-checkbox-group>
            <view v-if="userInfo.agreementTooltip" class="tooltip">
              <view />
              <text class="text"> 请先阅读并同意协议 </text>
            </view>
          </view>
          <view class="agreement-text" :class="userInfo.isShake ? 'shake' : ''" @tap="checkboxChange(!userInfo.agreement)">
            我已阅读并同意
            <text v-for="item in agreementOp" :key="item.name" class="path"> 《 {{ item.name }} 》 </text>、
            并授权本系统使用本系统账户信息(如昵称、头像)进行同意管理
          </view>
        </view> -->

        <view class="btn">
          <u-button
            :class="isActiveBtn ? 'login-btn-activate' : 'login-btn'"
            :disabled="!isActiveBtn"
            text="登 录"
            @tap="login"
          />
          <!-- #ifdef WEB -->

          <view class="qw-box">
            <text class="tag"> 或通过以下方式登录 </text>
            <view class="qiwei">
              <a v-if="!loading" href="http://mes.cnrecyc.com/api/auth/wxAuth/login"><view class="iconfont icon-qiwei" /></a>
            </view>
          </view>
          <!-- #endif -->
        </view>
      </uni-forms>
    </view>
  </view>
</template>
<script setup lang="ts" name="">
const theme = useThemeStore().theme;
const userStore = useUserStore();
let useVersionCode = ref("");

// const globalTheme = useThemeStore();

onLoad(() => {
  userInfo.username = useValue("lmf", uni.getStorageSync("login_name") || "");

  userInfo.password = useValue("123456", "");
  // app有保存密码
  if (isAPP()) {
    userInfo.password = uni.getStorageSync("login_password") || "";
    getVersion();
  }
  if (!isAPP()) getCode();
});

const getVersion = () => {
  plus.runtime.getProperty(plus.runtime.appid, async info => {
    useVersionCode.value = info.versionCode;
  });
};

// const agreementOp = [
//   {
//     name: "用户协议",
//     path: ""
//   },
//   {
//     name: "隐私政策",
//     path: ""
//   }
// ];
const rules = {
  username: [
    {
      required: true,
      message: "请输入账号",
      trigger: ["blur"]
    }
  ]
};

const placeholderStyle = `fontSize:16px;`;

let loading = ref(false);
let code = ref();
const userInfo = reactive({
  username: "",
  password: "",
  verificationCode: "",
  // 协议是否勾选
  agreement: true,
  // 是否使用震动动画
  isShake: false,
  // 协议未勾选提示框是否显示
  agreementTooltip: false,
  time: null
});

const isActiveBtn = computed(() => {
  if (!userInfo.username || !userInfo.password) {
    return false;
  }
  return true;
});

const getCode = async () => {
  // 是否从企微登录页面重定向页面过来的
  code.value = location?.href;
  if (code.value.indexOf("code=") !== -1) {
    useGlobalStore().setMessage("获取用户信息");
    loading.value = true;
    userStore.setToken("");
    try {
      const data = await wxAuthGetUser({ code: code.value });
      const { token, userObj } = data;
      const { username: name } = userObj;
      uni.setStorageSync("login_name", name);
      userStore.setToken(token);
      userStore.setUserInfo(userObj);
      useGlobalStore().setMessage("登录成功即将跳转首页");

      if (!isAPP()) uni.setStorageSync("url_code", "login_url_code");
      // await getConfig();

      // 获取用户权限
      const auth = await userGetAuthBySysUser({ username: name });
      useAuthStore().getAuthBySysUser(auth);
      loading.value = false;
      uni.redirectTo({
        url: "/pages/home/index"
      });
    } catch (error) {
      loading.value = false;
      useGlobalStore().setMessage("获取权限失败", "error");
    }
  }
};

const login = async () => {
  // const { agreement } = userInfo;
  // if (!agreement) {
  //   Object.assign(userInfo, {
  //     isShake: true,
  //     agreementTooltip: true
  //   });
  //   clearTimeout(userInfo.time);
  //   setTimeout(() => {
  //     userInfo.isShake = false;
  //   }, 500);
  //   userInfo.time = setTimeout(() => {
  //     userInfo.agreementTooltip = false;
  //   }, 2000);
  // }
  // console.log(1);

  userStore.setToken("");
  const { username, password } = userInfo;
  try {
    const data = await loginCheck({ username, password });

    const { token, userObj } = data;
    uni.setStorageSync("login_name", username);
    // app保存密码
    if (isAPP()) uni.setStorageSync("login_password", password);
    userStore.setToken(token);
    userStore.setUserInfo(userObj);
    // await getConfig();
    // 放入值用于跳转首页重新获取wx权限
    if (!isAPP()) uni.setStorageSync("url_code", "login_url_code");

    // 获取用户权限
    const auth = await userGetAuthBySysUser({ username });

    useAuthStore().getAuthBySysUser(auth);

    uni.redirectTo({
      url: "/pages/home/index"
    });
  } catch (error) {
    console.log();
  }
};
// const checkboxChange = (flag: boolean) => {
//   userInfo.agreement = flag;
// };
</script>
<style lang="scss" scoped src="./login.scss"></style>
<style lang="scss">
.login-form {
  :deep(.uni-input-input) {
    font-size: 18px !important;
    font-weight: bold !important;
  }
}
</style>
